package configtools

import (
	log "github.com/sirupsen/logrus"
	"github.com/spf13/viper"
	"strings"
)

const (
	INCLUSTER = "INCLUSTER"
)

// GlobalConfiguration 读取并解析application.yaml中的配置
var GlobalConfiguration *viper.Viper

// DatabaseConfiguration 尝试读取/config/pgconfig.yaml中的内容，如果不存在
var DatabaseConfiguration *viper.Viper

// EnvConfiguration 读取环境变量
var EnvConfiguration *viper.Viper

func init() {
	initGlobalConfiguration()
	initDatabaseConfiguration()
	initEnvConfiguration()
}

func GetRegisterPublicKeyFile() (dirLocation string, publicKeyFileNameWithSuffix string) {
	dirLocation = GlobalConfiguration.GetString("crypt.registerCenter.dirLocation")
	publicKeyFileNameWithSuffix = GlobalConfiguration.GetString("crypt.registerCenter.pkName")
	dirLocation, _ = strings.CutSuffix(dirLocation, "/")
	return
}

func initGlobalConfiguration() {
	GlobalConfiguration = viper.New()
	GlobalConfiguration.SetConfigName("application")
	GlobalConfiguration.AddConfigPath(".")
	GlobalConfiguration.AddConfigPath("../")    // 对于测试文件，需要回到cybertwin目录下
	GlobalConfiguration.AddConfigPath("../../") // 对于测试文件，需要回到cybertwin目录下
	GlobalConfiguration.SetConfigType("yaml")
	GlobalConfiguration.SetDefault("redis.addr", "localhost:6379")
	if err := GlobalConfiguration.ReadInConfig(); err != nil {
		log.Errorln("[configtools]-[解析配置]-无法找到application.yaml配置文件" + err.Error())
		return
	}
}

func initDatabaseConfiguration() {
	DatabaseConfiguration = viper.New()
	DatabaseConfiguration.SetConfigName("pgconfig")
	DatabaseConfiguration.AddConfigPath("/config")
	DatabaseConfiguration.SetConfigType("yaml")
	if err := DatabaseConfiguration.ReadInConfig(); err != nil {
		log.Infoln("[configtools]-[解析配置]-无法找到/config/pgconfig.yaml配置文件:" + err.Error())
		return
	}
}

func initEnvConfiguration() {
	EnvConfiguration = viper.New()
	EnvConfiguration.AutomaticEnv() // 读取环境变量
	if !EnvConfiguration.IsSet(INCLUSTER) {
		log.Infoln("[configtools]-[解析配置]-未查询到INCLUSTER环境变量，故将其设置为false")
		EnvConfiguration.Set(INCLUSTER, false)
	}
}
